package com.itheima.controller;

import com.itheima.pojo.Result;
import com.itheima.utils.AliOssUtil;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
public class FileUploadController {

    /*@PostMapping("/upload")
    public Result<String> upload(MultipartFile file) throws Exception {
        //把文件的内容存储到本地磁盘上
        String originalFilename = file.getOriginalFilename();
        //保证文件的名字是唯一的,从而防止文件覆盖
        String filename = UUID.randomUUID().toString()+originalFilename.substring(originalFilename.lastIndexOf("."));
        //file.transferTo(new File("C:\\Users\\Administrator\\Desktop\\files\\"+filename));
        String url = AliOssUtil.uploadFile(filename,file.getInputStream());
        return Result.success(url);
    }*/

    @PostMapping("/upload")
    public Result<String> upload(@RequestParam(value = "coverImg", required = false) MultipartFile file) throws Exception {
        // 检查文件是否为空
        if (file == null || file.isEmpty()) {
            // 返回默认图片URL
            String defaultUrl = "https://ts3.tc.mm.bing.net/th/id/OIP-C.KGHgOmsQerzKIGXujaPMAgAAAA?cb=12&rs=1&pid=ImgDetMain&o=7&rm=3";
            return Result.success(defaultUrl);
        }

        // 把文件的内容存储到本地磁盘上
        String originalFilename = file.getOriginalFilename();
        // 保证文件的名字是唯一的,从而防止文件覆盖
        String filename = UUID.randomUUID().toString() + originalFilename.substring(originalFilename.lastIndexOf("."));

        // 创建本地存储目录
        String uploadDirPath = "D:\\code\\big-event\\files\\";
        File uploadDir = new File(uploadDirPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdirs();
        }

        // 保存文件到本地磁盘
        String filePath = uploadDirPath + filename;
        file.transferTo(new File(filePath));

        // 返回本地文件访问URL（需要配置静态资源映射）
        String url = "/files/" + filename;
        return Result.success(url);
    }

}
